// useMapScale.js
import { ref, onMounted, onUnmounted } from 'vue';
import { GET_MAPBOX_MAP } from './map-utils';

export function useMapScale() {
  const scale = ref('');
  let mapboxInstance = null;

  onMounted(() => {
    setTimeout(() => {
      mapboxInstance = GET_MAPBOX_MAP();

      if (mapboxInstance) {
        mapboxInstance.on('zoom', updateMapboxScale);
        updateMapboxScale(); // 初始更新
      }
    }, 5e2);
  });

  // Mapbox GL的比例尺计算逻辑
  function updateMapboxScale() {
    const zoom = mapboxInstance.getZoom();
    const center = mapboxInstance.getCenter();
    const latitude = center.lat;

    // 将纬度转换为弧度
    const latRad = (latitude * Math.PI) / 180;

    // 计算每像素代表的实际距离（米）
    const metersPerPixel = (156543.03 * Math.cos(latRad)) / Math.pow(2, zoom);

    // 计算102像素代表的实际距离
    const distanceFor102px = metersPerPixel * 51;

    if (distanceFor102px > 1000) {
      scale.value = `${(distanceFor102px / 1000).toFixed(3) * 1}公里`;
    } else {
      scale.value = `${distanceFor102px.toFixed(0) * 1}米`;
    }
  }

  onUnmounted(() => {
    if (mapboxInstance) {
      mapboxInstance.off('zoom', updateMapboxScale);
    }
  });

  return { scale };
}
